package cn.walls1717.wallsmall.search.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.walls1717.wallsmall.common.pojo.to.es.SkuEsModel;
import cn.walls1717.wallsmall.search.feign.ProductFeignService;
import cn.walls1717.wallsmall.search.service.MallSearchService;
import cn.walls1717.wallsmall.search.vo.AttrRespVO;
import cn.walls1717.wallsmall.search.vo.BrandEntity;
import cn.walls1717.wallsmall.search.vo.SearchParam;
import cn.walls1717.wallsmall.search.vo.SearchResult;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static cn.walls1717.wallsmall.search.config.ESConfig.COMMON_OPTIONS;
import static cn.walls1717.wallsmall.search.constant.EsConstant.PRODUCT_INDEX;
import static cn.walls1717.wallsmall.search.constant.EsConstant.PRODUCT_PAGESIZE;

/**
 * @author walls1717
 * @since 2022/11/06 10:42
 **/
@Slf4j
@Service
public class MallSearchServiceImpl implements MallSearchService {
    @Resource
    private RestHighLevelClient client;
    @Resource
    private ProductFeignService productFeignService;

    /**
     * 根据检索条件检索
     *
     * @param param 检索的所有参数
     * @return 检索结果
     */
    @Override
    public SearchResult search(SearchParam param) {
        SearchRequest searchRequest = buildSearchRequest(param);
        SearchResult result = null;
        try {
            SearchResponse response = client.search(searchRequest, COMMON_OPTIONS);
            result = buildSearchResult(response, param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 构建检索请求
     *
     * @return 检索请求
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // must模糊匹配
        if (!StrUtil.isEmpty(param.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }
        // filter按照三级分类id查询
        if (param.getCatalog3Id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        // filter按照品牌id查询
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }
        // filter按照指定属性查询
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            // attrs=1_5寸:8寸&attrs=2_16G:8G
            for (String attrStr : param.getAttrs()) {
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                String[] s = attrStr.split("_");
                String attrId = s[0];
                String[] attrValues = s[1].split(":");
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }
        // filter按照是否有库存查询
        if (param.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }
        // filter按照价格区间查询
        if (!StrUtil.isEmpty(param.getSkuPrice())) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] s = param.getSkuPrice().split("_");
            if (s.length == 2) {
                rangeQuery.gte(s[0]).lte(s[1]);
            } else if (s.length == 1) {
                if (param.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(s[0]);
                }
                if (param.getSkuPrice().endsWith("_")) {
                    rangeQuery.gte(s[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }
        // 封装所有查询条件
        sourceBuilder.query(boolQuery);

        // 排序
        if (!StrUtil.isEmpty(param.getSort())) {
            String sort = param.getSort();
            String[] s = sort.split("_");
            SortOrder order = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(s[0], order);
        }

        // 分页
        sourceBuilder.from((param.getPageNum() - 1) * PRODUCT_PAGESIZE);
        sourceBuilder.size(PRODUCT_PAGESIZE);

        // 高亮
        if (!StrUtil.isEmpty(param.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }

        // 聚合分析
        // 品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg");
        brandAgg.field("brandId").size(50);
        // 品牌聚合子聚合 -> 品牌名聚合
        brandAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        // 品牌聚合子聚合 -> 品牌图片聚合
        brandAgg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brandAgg);

        // 分类聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalogAgg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalogAgg);

        // 属性聚合
        NestedAggregationBuilder attrAgg = AggregationBuilders.nested("attr_agg", "attrs");
        // 聚合出所有attrId
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        // attr_id_agg子聚合 -> 属性名聚合
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        // attr_id_agg子聚合 -> 属性值聚合
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attrAgg.subAggregation(attrIdAgg);
        sourceBuilder.aggregation(attrAgg);

        log.info("构建的DSL语句 -> {}", sourceBuilder);

        return new SearchRequest(new String[] {PRODUCT_INDEX}, sourceBuilder);
    }

    /**
     * 构建检索结果
     *
     * @param response 响应
     * @return 检索结果
     */
    private SearchResult buildSearchResult(SearchResponse response, SearchParam param) {
        SearchResult result = new SearchResult();
        SearchHits hits = response.getHits();
        // 封装product数据
        List<SkuEsModel> skuEsModels = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                // 有检索条件，将条件高亮
                if (!StrUtil.isEmpty(param.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String highlightSkuTitle = skuTitle.fragments()[0].string();
                    skuEsModel.setSkuTitle(highlightSkuTitle);
                }
                skuEsModels.add(skuEsModel);
            }
        }
        result.setProducts(skuEsModels);

        // 封装当前页
        result.setPageNum(param.getPageNum());

        // 封装总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);

        // 封装总页码
        int totalPages =
            (int)total % PRODUCT_PAGESIZE == 0 ? (int)total / PRODUCT_PAGESIZE : ((int)total / PRODUCT_PAGESIZE + 1);
        result.setTotalPages(totalPages);

        // pageNavs
        ArrayList<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

        // 封装品牌信息
        List<SearchResult.BrandVO> brandVOS = new ArrayList<>();
        ParsedLongTerms brandAgg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            SearchResult.BrandVO brandVO = new SearchResult.BrandVO();
            // 品牌id
            brandVO.setBrandId(bucket.getKeyAsNumber().longValue());
            // 品牌名
            String brandName = ((ParsedStringTerms)bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0)
                .getKeyAsString();
            brandVO.setBrandName(brandName);
            // 品牌图片
            String brandImg =
                ((ParsedStringTerms)bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();
            brandVO.setBrandImg(brandImg);

            brandVOS.add(brandVO);
        }
        result.setBrands(brandVOS);

        // 封装分类信息
        ParsedLongTerms catalogAgg = response.getAggregations().get("catalog_agg");
        List<SearchResult.CatalogVO> catalogVOS = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = catalogAgg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.CatalogVO catalogVO = new SearchResult.CatalogVO();
            // 分类id
            catalogVO.setCatalogId(bucket.getKeyAsNumber().longValue());
            // 分类名
            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVO.setCatalogName(catalogName);

            catalogVOS.add(catalogVO);
        }
        result.setCatalogs(catalogVOS);

        // 封装属性信息
        List<SearchResult.AttrVO> attrVOS = new ArrayList<>();
        ParsedNested attrAgg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            SearchResult.AttrVO attrVO = new SearchResult.AttrVO();
            // 属性id
            attrVO.setAttrId(bucket.getKeyAsNumber().longValue());
            // 属性名
            String attrName =
                ((ParsedStringTerms)bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            attrVO.setAttrName(attrName);
            // 属性值
            List<String> attrValues = ((ParsedStringTerms)bucket.getAggregations().get("attr_value_agg")).getBuckets()
                .stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(Collectors.toList());
            attrVO.setAttrValue(attrValues);
            attrVOS.add(attrVO);
        }
        result.setAttrs(attrVOS);

        // 封装面包屑导航数据
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            List<SearchResult.NavVO> navVOS = param.getAttrs().stream().map(attr -> {
                SearchResult.NavVO navVO = new SearchResult.NavVO();
                String[] s = attr.split("_");
                navVO.setNavValue(s[1]);
                AttrRespVO attrRespVO = productFeignService.attrInfo(Long.parseLong(s[0]));
                result.getAttrIds().add(Long.parseLong(s[0]));
                if (attrRespVO != null) {
                    navVO.setNavName(attrRespVO.getAttrName());
                } else {
                    navVO.setNavName(s[0]);
                }

                String replace = replaceQueryString(param, attr, "attrs");
                navVO.setLink("http://search.wallsmall.com/list.html?" + replace);
                return navVO;
            }).collect(Collectors.toList());
            result.setNavs(navVOS);
        }

        // 品牌
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            List<SearchResult.NavVO> navs = result.getNavs();
            SearchResult.NavVO navVO = new SearchResult.NavVO();
            List<BrandEntity> brands = productFeignService.listBrandsByBrandIds(param.getBrandId());
            navVO.setNavName("品牌");
            StringBuilder builder = new StringBuilder();
            String replace = null;
            for (BrandEntity brand : brands) {
                builder.append(brand.getName()).append(";");
                replace = replaceQueryString(param, brand.getBrandId().toString(), "brandId");
            }
            navVO.setNavValue(builder.toString());
            navVO.setLink("http://search.wallsmall.com/list.html?" + replace);
            navs.add(navVO);
        }

        log.info("result -> {}", result);
        return result;
    }

    private String replaceQueryString(SearchParam param, String value, String key) {
        String encode = null;
        try {
            encode = URLEncoder.encode(value, "UTF-8");
            encode = encode.replace("+", "%20");
            encode = encode.replace("%28", "(");
            encode = encode.replace("%29", ")");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return param.get_queryString().replace("&" + key + "=" + encode, "");
    }
}
